/*
 * Copyright (c) 2008-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.blogclient.profwizard;

import java.awt.CardLayout;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JLabel;

import org.panteleyev.blogclient.BloggerFrame;
import org.panteleyev.blogclient.IXmlRpcBased;
import org.panteleyev.blogclient.ProfileDialog;
import org.panteleyev.blogclient.SupportedService;
import org.panteleyev.blogclient.UserProfile;
import org.panteleyev.blogclient.UserProfileManager;
import org.panteleyev.flickr.FLUserProfile;

/**
 *
 * @author  Petr Panteleyev
 */
public class NewProfileWizard extends ProfileDialog {
    static final String ACCOUNT_TYPE_PAGE = "typePanel";
    static final String USER_DATA_PAGE = "userDataPanel";
    static final String PROFILE_OPTIONS_PAGE = "profOptionsPanel";
    static final String FLICKR_AUTH_PAGE = "flickrAuthPage";

    /* Controls */
    private JButton nextButton;
    private JButton prevButton;
    private JButton okButton;

    private CardLayout centerLayout;
    private CardLayout titleLayout;

    /* Panels */
    ProfileTypeSelectionPanel typePanel;
    UserCredentialsPanel userDataPanel;
    ProfileOptionsPanel profOptionsPanel;
    FlickrAuthPanel flickrAuthPanel;

    HashMap<String,IWizardPage> pages = new HashMap<String,IWizardPage>(4);
    IWizardPage currPage;

    public NewProfileWizard(BloggerFrame parent) {
        super(parent);
        initComponents();
        createButtons();

        titleLayout = new CardLayout(10, 10);
        titlePanel.setLayout(titleLayout);

        titlePanel.add(new JLabel(L10N.PROFILE_TYPE_TITLE_TEXT.s()), ACCOUNT_TYPE_PAGE);
        titlePanel.add(new JLabel(L10N.USER_DATA_TITLE_TEXT.s()), USER_DATA_PAGE);
        titlePanel.add(new JLabel(L10N.PROFILE_OPTIONS_TITLE_TEXT.s()), PROFILE_OPTIONS_PAGE);
        titlePanel.add(new JLabel("Flickr"), FLICKR_AUTH_PAGE);

        centerLayout = new CardLayout();
        topPanel.setLayout(centerLayout);

        pages.put(ACCOUNT_TYPE_PAGE, typePanel = new ProfileTypeSelectionPanel());
        topPanel.add(typePanel, ACCOUNT_TYPE_PAGE);

        pages.put(USER_DATA_PAGE, userDataPanel = new UserCredentialsPanel());
        topPanel.add(userDataPanel, USER_DATA_PAGE);

        pages.put(PROFILE_OPTIONS_PAGE, profOptionsPanel = new ProfileOptionsPanel());
        topPanel.add(profOptionsPanel, PROFILE_OPTIONS_PAGE);

        pages.put(FLICKR_AUTH_PAGE, flickrAuthPanel = new FlickrAuthPanel());
        topPanel.add(flickrAuthPanel, FLICKR_AUTH_PAGE);

        currPage = typePanel;

        pack();
        showPage(ACCOUNT_TYPE_PAGE);
    }

    public String getProfileName() {
        return profOptionsPanel.getProfileName();
    }

    public String getUserName() {
        return userDataPanel.getUserName();
    }

    public String getPassword() {
        return userDataPanel.getPassword();
    }

    public boolean getStorePassword() {
        return userDataPanel.getStorePassword();
    }

    private void createButtons() {
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        buttonPanel.add(Box.createHorizontalGlue());

        prevButton = new JButton(L10N.PREV_BUTTON.s());
        prevButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                String newPageString = currPage.getPrevPage();
                if (newPageString != null) {
                    showPage(newPageString);
                }
            }
        });
        buttonPanel.add(prevButton);

        nextButton = new JButton(L10N.NEXT_BUTTON.s());
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                if (currPage.isNextAllowed()) {
                    String newPageString = currPage.getNextPage();
                    if (newPageString != null) {
                        showPage(newPageString);
                    }
                }
            }
        });
        buttonPanel.add(nextButton);

        buttonPanel.add(createCancelButton());

        okButton = createOkButton();
        buttonPanel.add(okButton);
        okButton.setText(L10N.FINISH_BUTTON.s());
    }

    private void showPage(String pageString) {
        titleLayout.show(titlePanel, pageString);
        centerLayout.show(topPanel, pageString);
        currPage = pages.get(pageString);

        prevButton.setEnabled(currPage.getPrevPage() != null);
        nextButton.setEnabled(currPage.getNextPage() != null);
        okButton.setEnabled(currPage.getNextPage() == null);
    }

    @Override
    protected void onOk() {
        if (currPage.isNextAllowed()) {
            String name = getProfileName();
            SupportedService service = typePanel.getSelectedService();
            UserProfile prof = UserProfileManager.createUserProfile(service.getProfileType(), name, service.getName());
            prof.generateCacheId();
            // fill data
            prof.setUserName(getUserName());
            boolean bStore = getStorePassword();
            prof.setStorePasswd(bStore);
            if (bStore) {
                prof.setPassword(getPassword());
            }
            prof.setDefaultProfile(profOptionsPanel.getMakeDefault());

            if (prof instanceof IXmlRpcBased) {
                ((IXmlRpcBased)prof).setXmlRpc(typePanel.getXmlRpc());
            }

            if (prof instanceof FLUserProfile) {
                ((FLUserProfile)prof).setAuthResult(flickrAuthPanel.getAuthResult());
            }

            UserProfileManager.addProfile(prof);
            UserProfileManager.saveProfiles();

            super.onOk();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        titlePanel = new javax.swing.JPanel();
        topPanel = new javax.swing.JPanel();
        buttonPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(TITLE_NEW);
        setResizable(false);
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));

        titlePanel.setBackground(new java.awt.Color(255, 255, 255));
        titlePanel.setLayout(null);
        getContentPane().add(titlePanel);

        topPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
        topPanel.setLayout(null);
        getContentPane().add(topPanel);

        buttonPanel.setLayout(new javax.swing.BoxLayout(buttonPanel, javax.swing.BoxLayout.LINE_AXIS));
        getContentPane().add(buttonPanel);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JPanel titlePanel;
    private javax.swing.JPanel topPanel;
    // End of variables declaration//GEN-END:variables

}
